package com.sand.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.sand.entity.AlipayModel;
import com.sand.service.IContractService;
import com.sand.util.AlipayConfig;
import com.sand.util.AlipayUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class AlipayController {

    @Resource(name = "contractService")
    private IContractService contractService;

    private void servletInit(HttpServletRequest request,
                             HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
    }

    /* 订单接口 */
    @PostMapping(value = "/alipay")
    public void alipay(HttpServletResponse response,Integer orderId,Integer price) throws AlipayApiException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String out_trade_no= String.valueOf(orderId);
        String subject="好客租房租金支付";
        String total_amount= String.valueOf(price);
        String body="";
        String result= AlipayUtil.connect(new AlipayModel()
                .setBody(body)
                .setOut_trade_no(out_trade_no)
                .setTotal_amount(new StringBuffer().append(total_amount))
                .setSubject(subject));
        response.getWriter().print(result);
    }

    @GetMapping(value = "/alipay/complete")
    public ModelAndView complete(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        servletInit(request,response);
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
        ModelAndView mav=new ModelAndView("renting/pages/tenant/wallet");
        if(signVerified) {
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaa");
//            //商户订单号
//            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//
//            //支付宝交易号
//            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//
//            //付款金额
//            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            mav.addObject("code","OK");
            mav.addObject("orderId",new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8"));

            boolean bln = contractService.updateBillStatus(Integer.parseInt(request.getParameter("out_trade_no")), "支付宝");
            System.out.println("==========================================="+bln+">>>"+request.getParameter("out_trade_no"));




        }else {
            System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbbbb");
            mav.addObject("code","NO");
        }
        mav.addObject("gofor","jsp/renting/pages/tenant/order.jsp");
        return mav;
    }

    @PostMapping(value = "/alipay/notify")
    public void notify(HttpServletResponse response, HttpServletRequest request) throws IOException, AlipayApiException, ServletException {
        servletInit(request,response);
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("111111111111111111");
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type); //调用SDK验证签名
        if(signVerified) {
            System.out.println("22222222222222222222");
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                System.out.println("3333333333333333333333333");
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                System.out.println("4444444444444444444444");
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
//                request.getRequestDispatcher(request.getContextPath()+"/alipay/complete").forward(request,response);



            }
            response.getWriter().write("OK");
        }else{
            System.out.println("555555555555555555555555");
            response.getWriter().write("NO");
        }
    }

}
